<?php
require '../db.php';
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$settings_file = __DIR__ . '/../settings.json';
$default_settings = [
    'title' => '私人网盘',
    'max_upload_size' => 10 * 1024 * 1024,
    'allowed_file_types' => ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'doc', 'docx'],
    'registration_enabled' => true,
    'announcement' => '',
    'site_domain' => 'http://localhost',
    'upload_dir' => 'uploads/',
    'max_files_per_user' => 100,
    'theme' => 'dark',
    'file_expiry_days' => 0
];
$settings = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : $default_settings;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        error_log("CSRF validation failed in settings.php");
        die("CSRF 验证失败！");
    }

    $settings['title'] = trim($_POST['title']);
    $settings['max_upload_size'] = (int)$_POST['max_upload_size'] * 1024 * 1024;
    $allowed_types_input = trim(strtolower($_POST['allowed_file_types']));
    $settings['allowed_file_types'] = empty($allowed_types_input) ? [] : array_filter(array_map('trim', explode(',', $allowed_types_input)));
    $settings['registration_enabled'] = isset($_POST['registration_enabled']) ? true : false;
    $settings['announcement'] = trim($_POST['announcement']);
    $settings['site_domain'] = rtrim(trim($_POST['site_domain']), '/');
    $settings['upload_dir'] = rtrim(trim($_POST['upload_dir']), '/') . '/';
    $settings['max_files_per_user'] = (int)$_POST['max_files_per_user'];
    $settings['theme'] = $_POST['theme'];
    $settings['file_expiry_days'] = (int)$_POST['file_expiry_days'];

    if (file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) !== false) {
        header("Location: settings.php?success=1");
        exit;
    } else {
        error_log("Failed to write to $settings_file: " . error_get_last()['message']);
        die("保存失败，请检查文件权限！");
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网站设置</title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php">后台管理</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="../index.php">网站前台</a></li>
                    <li class="nav-item"><a class="nav-link" href="users.php">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="files.php">文件管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="categories.php">分类管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="settings.php">网站设置</a></li>
                    <li class="nav-item"><a class="nav-link" href="../logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container py-5">
        <h2>网站设置</h2>
        <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
            <div class="alert alert-success">设置保存成功！</div>
        <?php endif; ?>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="mb-3">
                <label for="title" class="form-label">网站标题</label>
                <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($settings['title']) ?>" required>
            </div>
            <div class="mb-3">
                <label for="max_upload_size" class="form-label">最大上传文件大小（MB）</label>
                <input type="number" class="form-control" id="max_upload_size" name="max_upload_size" value="<?= round($settings['max_upload_size'] / (1024 * 1024), 2) ?>" min="1" required>
            </div>
            <div class="mb-3">
                <label for="allowed_file_types" class="form-label">允许的文件类型（逗号分隔，例如：jpg,png,pdf）</label>
                <input type="text" class="form-control" id="allowed_file_types" name="allowed_file_types" value="<?= htmlspecialchars(is_array($settings['allowed_file_types']) ? implode(',', $settings['allowed_file_types']) : '') ?>" required>
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="registration_enabled" name="registration_enabled" <?= $settings['registration_enabled'] ? 'checked' : '' ?>>
                    <label class="form-check-label" for="registration_enabled">启用用户注册</label>
                </div>
            </div>
            <div class="mb-3">
                <label for="announcement" class="form-label">网站公告</label>
                <textarea class="form-control" id="announcement" name="announcement" rows="3"><?= htmlspecialchars($settings['announcement']) ?></textarea>
            </div>
            <div class="mb-3">
                <label for="site_domain" class="form-label">网站域名（例如 http://你的域名）</label>
                <input type="text" class="form-control" id="site_domain" name="site_domain" value="<?= htmlspecialchars($settings['site_domain']) ?>" required>
            </div>
            <div class="mb-3">
                <label for="upload_dir" class="form-label">文件存储路径（相对路径，例如 uploads/）</label>
                <input type="text" class="form-control" id="upload_dir" name="upload_dir" value="<?= htmlspecialchars($settings['upload_dir']) ?>" required>
            </div>
            <div class="mb-3">
                <label for="max_files_per_user" class="form-label">每用户最大文件数量</label>
                <input type="number" class="form-control" id="max_files_per_user" name="max_files_per_user" value="<?= $settings['max_files_per_user'] ?>" min="1" required>
            </div>
            <div class="mb-3">
                <label for="theme" class="form-label">网站主题</label>
                <select class="form-select" id="theme" name="theme">
                    <option value="dark" <?= $settings['theme'] === 'dark' ? 'selected' : '' ?>>暗色</option>
                    <option value="light" <?= $settings['theme'] === 'light' ? 'selected' : '' ?>>亮色</option>
                </select>
            </div>
            <div class="mb-3">
                <label for="file_expiry_days" class="form-label">文件过期时间（天，0表示不过期）</label>
                <input type="number" class="form-control" id="file_expiry_days" name="file_expiry_days" value="<?= $settings['file_expiry_days'] ?>" min="0" required>
            </div>
            <button type="submit" class="btn btn-primary">保存设置</button>
        </form>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>